"""
自定义分页组件
"""
from django.utils.safestring import mark_safe

class Pagination(object):
    def __init__(self, request, queryset, page_size=10,page_param='page', plus=5):
        self.page_param = page_param
        page = request.GET.get(page_param, "1")
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page
        self.page_size = page_size
        self.start = (page - 1) * page_size
        self.end = page * page_size
        self.page_queryset = queryset[self.start:self.end]
        total_count = queryset.count()
        total_page_count, div = divmod(total_count, page_size)
        total_page_count = total_page_count + 1 if div else total_page_count
        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        if self.page <= 5:
            start_page = 1
            end_page =self.page + self.plus + 1 + (10 - self.page - self.plus + 1)
        elif self.page >= self.total_page_count - 5:
            end_page = self.total_page_count + 1
            start_page = self.page - self.plus - (6 - (end_page - self.page))
        else:
            start_page = self.page - self.plus
            end_page = self.page + self.plus + 1  # 适应range的前取后不取

        # 页码
        page_str_list = []

        # 首页的按钮
        first_page = f'<li><a href="?page={1}">首页</a></li>'
        page_str_list.append(first_page)

        # 上一页的按钮
        if self.page > 1:
            prev = f'<li><a href="?page={self.page - 1}">上一页</a></li>'
            page_str_list.append(prev)
        else:
            prev = f'<li><a href="?page={self.page}">上一页</a></li>'
            page_str_list.append(prev)

        for i in range(start_page, end_page):
            if i == self.page:
                ele = f'<li class="active"><a href="?page={i}">{i}</a></li>'
            else:
                ele = f'<li><a href="?page={i}">{i}</a></li>'
            page_str_list.append(ele)

        # 下一页的按钮
        if self.page < self.total_page_count:
            next = f'<li><a href="?page={self.page + 1}">下一页</a></li>'
            page_str_list.append(next)
        else:
            next = f'<li><a href="?page={self.page}">下一页</a></li>'
            page_str_list.append(next)

        # 尾页的按钮
        last_page = f'<li><a href="?page={self.total_page_count}">尾页</a></li>'
        page_str_list.append(last_page)

        page_string = mark_safe("".join(page_str_list))
        return page_string